package masterjava.common.io;

import masterjava.common.logging.ServerLogger;
import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * User: gkislin
 * Date: 7/26/11
 */
public class IOUtil {
    private static final ServerLogger LOGGER = ServerLogger.get(IOUtil.class);

    // Use in finally !
    public static void close(Closeable ioResource) {
        if (ioResource != null) {
            try {
                ioResource.close();
            } catch (Exception e) {
                LOGGER.warn("Resource closing exception", e);
            }
        }
    }

    // read content from file
    public static String loadFile(File file) {
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            return IOUtils.toString(fr);
        } catch (FileNotFoundException e) {
            throw LOGGER.getIllegalStateException("File " + file.getPath() + " couldn't be found", e);
        } catch (IOException e) {
            throw LOGGER.getIllegalStateException("File " + file.getPath() + " read exception", e);
        } finally {
            IOUtil.close(fr);
        }
    }

    // write new file content
    public static void saveFile(File file, String newContent) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(file);
            IOUtils.write(newContent, fw);
        } catch (FileNotFoundException e) {
            throw LOGGER.getIllegalStateException("File " + file.getPath() + " couldn't be found", e);
        } catch (IOException e) {
            throw LOGGER.getIllegalStateException("File " + file.getPath() + " read exception", e);
        } finally {
            IOUtil.close(fw);
        }
    }
}
